package com.wanlian.router.ui.router;

import android.app.Activity;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.smart.android.ui.BaseActivity;
import com.smart.android.ui.app.IntentExtra;
import com.smart.android.utils.UIUtils;
import com.smart.android.widget.EditTextWithClear;
import com.wanlian.router.R;
import com.wanlian.router.bean.WifiSetting;
import com.wanlian.router.net.NetWorkingClient;
import com.wanlian.router.net.ResponseData;
import com.wanlian.router.net.internal.INetCallBack;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Hyu on 2018/9/12.
 * Email: fvaryu@qq.com
 */
public class NetworkSettingActivity extends BaseActivity implements TextWatcher, WifiSettingBindFragment.OnSettingListener {
    private static final String[] TYPES = new String[]{"WPA2", "WPA/WPA2", "无密码"};
    private static final String[] TYPES_Value = new String[]{"psk2", "psk-mixed", "none"};// none（不加密）/psk-mixed（WPA/WPA2混合加密）/psk2（WPA2加密）


    @BindView(R.id.ll_first)
    LinearLayout mFirst;
    @BindView(R.id.ll_second)
    LinearLayout mSecond;

    @BindView(R.id.rg_dns)
    RadioGroup mRadioGroup;

    @BindView(R.id.ll_pppoe)
    LinearLayout llPppoe;
    @BindView(R.id.ll_static_ip)
    LinearLayout llStaticIP;
    @BindView(R.id.ll_dynamic_ip)
    LinearLayout llDynmaicIP;

    @BindView(R.id.tv_wifi)
    TextView wifi;

    @BindView(R.id.tv_second)
    TextView tv_second;
    @BindView(R.id.tv_first)
    TextView tv_first;

    @BindView(R.id.tv_connect)
    TextView tv_connect;
    @BindView(R.id.et_account)
    EditTextWithClear et_account;
    @BindView(R.id.et_pwd)
    EditTextWithClear et_pwd;

    @BindView(R.id.et_ip)
    EditTextWithClear et_ip;
    @BindView(R.id.et_mask)
    EditTextWithClear et_mask;
    @BindView(R.id.et_gateway)
    EditTextWithClear et_gateway;
    @BindView(R.id.et_dns_1)
    EditTextWithClear et_dns_1;
    @BindView(R.id.et_dns_2)
    EditTextWithClear et_dns_2;

//    @BindView(R.id.et_dynamic_ip)
//    EditTextWithClear et_dynamic_ip;
//    @BindView(R.id.et_dynamic_mask)
//    EditTextWithClear et_dynamic_mask;
//    @BindView(R.id.et_dynamic_gateway)
//    EditTextWithClear et_dynamic_gateway;
//    @BindView(R.id.et_dynamic_dns)
//    EditTextWithClear et_dynamic_dns;

    @BindView(R.id.tab_layout)
    TabLayout mTabLayout;

    @BindView(R.id.viewpager)
    ViewPager viewpager;

    @BindView(R.id.tv_save)
    TextView tv_save;
    @BindView(R.id.image_check)
    ImageView image_check;
    @BindView(R.id.rg_d)
    RadioGroup rg_d;
    @BindView(R.id.rb_auto)
    RadioButton rb_auto;
    @BindView(R.id.rb_self)
    RadioButton rb_self;
    @BindView(R.id.et_dns1)
    EditTextWithClear et_dns1;
    @BindView(R.id.et_dns2)
    EditTextWithClear et_dns2;
    @BindView(R.id.tv_need)
    TextView tvNeed;
    @BindView(R.id.tv_need2)
    TextView tvNeed2;
    @BindView(R.id.view)
    View mView;
    WifiSetting wifiSetting = new WifiSetting();
    private boolean isConnected;
    private int wifiType;
    private boolean showPwd, showPwd1;

//    @BindView(R.id.line5)
//    View line5;

    @Override
    protected int layout() {
        return R.layout.activity_bing_networking_setting;
    }

    @OnClick(R.id.image_check)
    void check() {
        showPwd = !showPwd;
        if (showPwd) {
            image_check.setImageResource(R.drawable.eye_open_gray);
            et_pwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
        } else {
            image_check.setImageResource(R.drawable.eye_close_gray);
            et_pwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
        }

    }


    @Override
    public void initUI() {
        super.initUI();
        setTitle("网络配置");


        et_account.addTextChangedListener(this);
        et_pwd.addTextChangedListener(this);

        et_gateway.addTextChangedListener(this);
        et_mask.addTextChangedListener(this);
        et_dns_1.addTextChangedListener(this);
        et_ip.addTextChangedListener(this);

//        et_dynamic_gateway.addTextChangedListener(this);
//        et_dynamic_mask.addTextChangedListener(this);
//        et_dynamic_dns.addTextChangedListener(this);
//        et_dynamic_ip.addTextChangedListener(this);


        WifiManager wifiManager = (WifiManager) getApplication().getApplicationContext().getSystemService(WIFI_SERVICE);
        String ssid = wifiManager.getConnectionInfo().getSSID();
        wifi.setText(String.format("当前路由器WiFi网络为：%s", ssid));

        mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                switch (checkedId) {
                    case R.id.rb_pppoe: {
                        llPppoe.setVisibility(View.VISIBLE);
                        llStaticIP.setVisibility(View.GONE);
                        llDynmaicIP.setVisibility(View.GONE);

                        tv_connect.setText("拨号连接");
                    }
                    break;
                    case R.id.rb_static_ip: {
                        llStaticIP.setVisibility(View.VISIBLE);
                        llPppoe.setVisibility(View.GONE);
                        llDynmaicIP.setVisibility(View.GONE);
                        tv_connect.setText("保存设置");
                    }
                    break;
                    case R.id.rb_dynamic_ip: {
                        llStaticIP.setVisibility(View.GONE);
                        llPppoe.setVisibility(View.GONE);
                        llDynmaicIP.setVisibility(View.VISIBLE);
                        tv_connect.setText("保存设置");
                    }
                    break;
                }
            }
        });
        mRadioGroup.check(R.id.rb_pppoe);

        et_dns1.addTextChangedListener(this);
        et_dns2.addTextChangedListener(this);

        rg_d.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_self) {
                    tvNeed.setVisibility(View.VISIBLE);
                    tvNeed2.setVisibility(View.VISIBLE);
                    et_dns1.setEnabled(true);
                    et_dns2.setEnabled(true);

                    et_dns1.setHint("请输入DNS");
                    et_dns1.setText(null);
                    et_dns2.setText(null);
                    et_dns2.setHint("请输入DNS");
                    tv_connect.setEnabled(false);
                } else {
                    tvNeed.setVisibility(View.GONE);
                    tvNeed2.setVisibility(View.GONE);
                    et_dns1.setEnabled(false);
                    et_dns2.setEnabled(false);

                    et_dns1.setHint("系统自动分配DNS");
                    et_dns1.setText(null);
                    et_dns2.setText(null);
                    et_dns2.setHint("系统自动分配DNS");

                    tv_connect.setEnabled(true);
                }
            }
        });

    }

    @Override
    public void initData() {
        super.initData();
        SpannableString ss = new SpannableString("联网设置(第一步)");
        ss.setSpan(new RelativeSizeSpan(0.8f), 4, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new ForegroundColorSpan(getColorById(R.color.color_99)), 4, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_first.setText(ss);

        ss = new SpannableString("WiFi设置(第二步)");
        ss.setSpan(new RelativeSizeSpan(0.8f), 6, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        ss.setSpan(new ForegroundColorSpan(getColorById(R.color.color_99)), 6, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_second.setText(ss);


        viewpager.setAdapter(new FragmentStatePagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {
                WifiSettingBindFragment wifiSettingBindFragment = WifiSettingBindFragment.newInstance(position, wifiSetting);
                wifiSettingBindFragment.setOnSettingListener(NetworkSettingActivity.this);
                return wifiSettingBindFragment;
            }

            @Override
            public int getCount() {
                return 3;
            }

            @Nullable
            @Override
            public CharSequence getPageTitle(int position) {
                switch (position) {
                    case 0:
                        return "2.4G";
                    case 1:
                        return "5G";
                    case 2:
                        return "访客网络";
                }
                return super.getPageTitle(position);
            }
        });
        mTabLayout.setupWithViewPager(viewpager);
        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                wifiType = tab.getPosition();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        UIUtils.setIndicator(mTabLayout, 30, 30);
    }

    boolean formLogin() {
        return getIntent().getBooleanExtra(IntentExtra.EXTRA_BOOL, false);
    }

    @OnClick(R.id.tv_first)
    void first(TextView view) {
        view.setCompoundDrawablesWithIntrinsicBounds(0, 0, mFirst.getVisibility() == View.GONE
                ? R.drawable.up : R.drawable.down, 0);
        mFirst.setVisibility(mFirst.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);

    }

    @OnClick(R.id.tv_second)
    void second(TextView view) {
        view.setCompoundDrawablesWithIntrinsicBounds(0, 0, mSecond.getVisibility() == View.GONE
                ? R.drawable.up : R.drawable.down, 0);
        mSecond.setVisibility(mSecond.getVisibility() == View.GONE ? View.VISIBLE : View.GONE);

        if (mSecond.getVisibility() == View.VISIBLE) {
            mView.setVisibility(View.GONE);
//            line5.setVisibility(View.VISIBLE);
        } else {
            mView.setVisibility(View.VISIBLE);
//            line5.setVisibility(View.GONE);
        }
    }


    @OnClick(R.id.tv_save)
    void next() {

        NetWorkingClient.getInstance().settingWifi(getActivity(), true, true, wifiSetting, new INetCallBack() {
            @Override
            public void onFinish(ResponseData response, @Nullable Object o) {
                if (response.isSuccess()) {

                    showToast("保存成功");

//                    if (formLogin()) {
                    Intent data = new Intent();
                    data.putExtra(IntentExtra.EXTRA_BOOL, true);
                    setResult(Activity.RESULT_OK, data);
//                    }

                    finish();
                } else {
                    showToast(response.getMessage());
                }
            }
        });

    }


    @OnClick(R.id.tv_connect)
    void connect() {

        switch (mRadioGroup.getCheckedRadioButtonId()) {
            case R.id.rb_pppoe: {

                NetWorkingClient.getInstance().connectCall(getActivity(), et_account.getText().toString(), et_pwd.getText().toString(), new INetCallBack() {
                    @Override
                    public void onFinish(ResponseData response, @Nullable Object o) {
                        if (response.isSuccess()) {
                            isConnected = true;
                            showToast("连接成功");
                        } else {
                            showToast(response.getMessage());
                        }
                    }
                });
            }
            break;
            case R.id.rb_static_ip: {
                if ((et_dns_2.getText() != null && !TextUtils.isEmpty(et_dns_2.getText().toString())) && !v(et_dns_2.getText().toString())) {
                    showToast("请输入有效DNS");
                    return;
                }
                WifiSetting wifiSetting = new WifiSetting();
                wifiSetting.setSord("static");
//                wifiSetting.setDynamic_defaultNetWay(et_gateway.getText().toString());
//                wifiSetting.setDynamic_DNS(et_dns.getText().toString());
//                wifiSetting.setDynamic_subnetMask(et_mask.getText().toString());
//                wifiSetting.setDynamic_webAddress(et_ip.getText().toString());
                wifiSetting.setStatic_defaultNetWay(et_gateway.getText().toString());
                wifiSetting.setOneDNS(et_dns_1.getText().toString());
                wifiSetting.setTwoDNS(et_dns_2.getText().toString());
                wifiSetting.setStatic_subnetMask(et_mask.getText().toString());
                wifiSetting.setStatic_webAddress(et_ip.getText().toString());
                NetWorkingClient.getInstance().settingWifi(getActivity(), false,false, wifiSetting, new INetCallBack() {
                    @Override
                    public void onFinish(ResponseData response, @Nullable Object o) {
                        if (response.isSuccess()) {

                            showToast("设置成功");
                        } else {
                            showToast(response.getMessage());
                        }
                    }
                });
            }
            break;

            case R.id.rb_dynamic_ip: {
                WifiSetting wifiSetting = new WifiSetting();
                wifiSetting.setSord("dhcp");
                wifiSetting.setDynamicType(rg_d.getCheckedRadioButtonId() == R.id.rb_auto ? 0 : 1);
                if (rg_d.getCheckedRadioButtonId() != R.id.rb_auto) {
                    if ((et_dns2.getText() != null &&
                            !TextUtils.isEmpty(et_dns2.getText().toString()))
                            && !v(et_dns2.getText().toString())) {
                        showToast("请输入有效DNS");
                        return;
                    }
                    wifiSetting.setOneDNS(et_dns1.getText().toString());
                    wifiSetting.setTwoDNS(et_dns2.getText().toString());
                }
//                wifiSetting.setDynamic_defaultNetWay(et_dynamic_gateway.getText().toString());
//                wifiSetting.setDynamic_DNS(et_dynamic_dns.getText().toString());
//                wifiSetting.setDynamic_subnetMask(et_dynamic_mask.getText().toString());
//                wifiSetting.setDynamic_webAddress(et_dynamic_ip.getText().toString());
//                wifiSetting.setStatic_defaultNetWay(et_gateway.getText().toString());
//                wifiSetting.setStatic_DNS(et_dns.getText().toString());
//                wifiSetting.setStatic_subnetMask(et_mask.getText().toString());
//                wifiSetting.setStatic_webAddress(et_ip.getText().toString());
                NetWorkingClient.getInstance().settingWifi(getActivity(), false, false, wifiSetting, new INetCallBack() {
                    @Override
                    public void onFinish(ResponseData response, @Nullable Object o) {
                        if (response.isSuccess()) {

                            showToast("设置成功");
                        } else {
                            showToast(response.getMessage());
                        }
                    }
                });
            }
            break;
        }


    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {


        switch (mRadioGroup.getCheckedRadioButtonId()) {
            case R.id.rb_pppoe: {
                tv_connect.setEnabled(et_account.getText() != null &&
                        !TextUtils.isEmpty(et_account.getText().toString()) &&
                        et_pwd.getText() != null &&
                        !TextUtils.isEmpty(et_pwd.getText().toString()));
            }
            break;
            case R.id.rb_static_ip: {
                tv_connect.setEnabled(
                        et_ip.getText() != null && v(et_ip.getText().toString()) &&
                                et_mask.getText() != null && v(et_mask.getText().toString()) &&
                                et_dns_1.getText() != null && v(et_dns_1.getText().toString()) &&
                                et_gateway.getText() != null && v(et_gateway.getText().toString())

                );
            }
            break;

            case R.id.rb_dynamic_ip: {
                tv_connect.setEnabled(
                        et_dns1.getText() != null && v(et_dns1.getText().toString())
                );
            }
            break;
        }


    }

    private boolean v(String string) {
        if (TextUtils.isEmpty(string)) {
            return false;
        }
        String regex = "(2[5][0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})";
        return string.matches(regex);
    }

    @Override
    public void onSetting(int type, WifiSetting wifiSetting) {
        int ok = 0;
        if (!TextUtils.isEmpty(wifiSetting.getTwoWifiAccount()) && !TextUtils.isEmpty(wifiSetting.getTwoWifiPassWord())) {
            ok++;
        }
        if (!TextUtils.isEmpty(wifiSetting.getFiveAccount()) && !TextUtils.isEmpty(wifiSetting.getFiveWifiPassWord())) {
            ok++;
        }
        if (!TextUtils.isEmpty(wifiSetting.getCustomerWifiAccount()) && !TextUtils.isEmpty(wifiSetting.getCustomerWifiPassWord())) {
            ok++;
        }
        tv_save.setEnabled(isConnected && ok == 3);
    }
}
